package com.ymj.netty.server.medium;


import com.ymj.netty.annotation.Remote;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 *  @Description: 初始化中间人拥有的map，将所有远程调用方法的method和bean等信息放到里面，方便其反射调用
 *  @author: yanmj
 *  @Date: 2020-06-07
 */
@Component
public class InitializeMedium implements BeanPostProcessor {


    /**
     * bean初始化之前执行
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    /**
     * bean初始化之后执行
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        //将所有远程调用方法放到一个map中，方便反射
        if(bean.getClass().isAnnotationPresent(Remote.class)){
            Method[] declaredMethods = bean.getClass().getInterfaces()[0].getDeclaredMethods();
            for(Method m : declaredMethods){
                String name = bean.getClass().getInterfaces()[0].getName()+"."+m.getName();
                BeanMethod beanMethod = new BeanMethod();
                beanMethod.setBean(bean);
                beanMethod.setMethod(m);
                Medium.allMethodMap.put(name,beanMethod);
                //例：<name="com.ymj.api.UserApi.save",
                // beanMethod.bean="userApiImpl",beanMethod.method="save">
            }
        }
        return bean;
    }
}
